<?php
/**
 * Created by PhpStorm.
 * User: ASUS
 * Date: 2018/4/2
 * Time: 21:00
 */

namespace Servers;

class Server
{
    private $serv;

    public function __construct() {
        $this->serv = new \swoole_server("0.0.0.0", 9501, SWOOLE_PROCESS, SWOOLE_SOCK_UDP);
        $this->serv->set(array(
            'worker_num' => 4,  // 指定启动的worker进程数。建议开启的worker进程数为cpu核数的1-4倍。
            'daemonize' => false,
            'max_request' => 10000, // worker进程允许处理的最大任务数。 说明：设置该值后，每个worker进程在处理完max_request个请求后就会自动重启。设置该值的主要目的是为了防止worker进程处理大量请求后可能引起的内存溢出。
            'dispatch_mode' => 2,
            'debug_mode'=> 1,

        ));

        // 第二数组参数[当前类， 当前类的方法]
        $this->serv->on('Start', array($this, 'onStart'));
        $this->serv->on('Packet', array($this, 'onPacket'));

        $this->serv->start();
    }

    public function onStart(\swoole_server  $serv ) {
        echo "Start\n\n";
    }


    /**
     *  UDP协议下只有onReceive事件，没有onConnect/onClose事件
     *  新版本，onReceive作废，onPacket替换
     */
    public function onPacket( \swoole_server $serv, string $data, array $client_info){
        print_r($data);
        echo "\n";
        print_r($client_info);
        $serv->sendto($client_info['address'], $client_info['port'], "Server ".$data);
    }


}
// 启动服务器
$server = new Server();